<template>
  <div class="historical-chart">
    <div class="chart-container">
      <v-chart 
        class="chart"
        v-if="!isNoData || displayData.length > 0"
        :option="chartOption"
        :autoresize="true"
        ref="chartRef"
      />
      <div v-else class="no-data-message">
        无数据
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  MarkLineComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  MarkLineComponent
])

const props = defineProps({
  historicalData: {
    type: Array,
    default: () => []
  },
  totalDuration: {
    type: Number,
    default: 40 // 默认40秒，可以从父组件传入
  },
  isPlaying: {
    type: Boolean,
    default: false
  },
  currentPlaybackTime: {
    type: Number,
    default: 0 // 当前播放时间（秒），从父组件传入
  },
  startTime: {
    type: Number,
    default: null // 开始时间（毫秒），从父组件传入，可选
  }
})

const emit = defineEmits(['playback-complete', 'no-data'])

const chartRef = ref()
const currentIndex = ref(0)
const isNoData = ref(false) // 标记是否无数据
// 移除displayedData响应式变量，直接使用displayData计算属性
// 存储所有数据点的全局变量，确保组件重新挂载时不会丢失数据
const selectedAllDataPoints = ref([])
// 存储当前进度条的播放时间（秒）
const currentProgressTime = ref(0)

// 页面加载时打印传入的数据点数据
onMounted(() => {
  console.log('HistoricalChart component mounted with historicalData:', props.historicalData)
  console.log('Historical data length:', props.historicalData?.length || 0)
})

const hasData = computed(() => props.historicalData && props.historicalData.length > 0)
const maxIndex = computed(() => hasData.value ? props.historicalData.length - 1 : 0)

const currentTime = computed(() => {
  if (hasData.value && currentIndex.value < props.historicalData.length) {
    return props.historicalData[currentIndex.value].time || ''
  }
  return ''
})

// 辅助函数：将时间字符串(HH:mm:ss.SSS或HH:mm:ss:SSS)转换为毫秒数
function convertTimeStrToMs(timeStr) {
  try {
    // 支持两种时间格式：HH:mm:ss.SSS 和 HH:mm:ss:SSS
    const [hours, minutes, seconds, milliseconds] = timeStr.split(/[:.]/).map(Number);
    return hours * 3600000 + minutes * 60000 + seconds * 1000 + milliseconds;
  } catch (error) {
    console.error('时间字符串转毫秒错误:', error, '时间字符串:', timeStr);
    return 0;
  }
}

// 当前显示的数据
// 根据播放时间动态加载数据点
const displayData = computed(() => {
  if (!hasData.value) {
    isNoData.value = true
    return []
  }
  
  // 确保selectedAllDataPoints已初始化，并保证数据按时间升序排列
  if (selectedAllDataPoints.value.length === 0 && props.historicalData.length > 0) {
    // 对数据点按时间进行排序 - 使用sysTime（直接从时间字符串转换的毫秒数）
    selectedAllDataPoints.value = [...props.historicalData].sort((a, b) => {
      const timeA = a.sysTime || (typeof a.time === 'string' ? convertTimeStrToMs(a.time) : 0);
      const timeB = b.sysTime || (typeof b.time === 'string' ? convertTimeStrToMs(b.time) : 0);
      return timeA - timeB;
    });
    console.log('Initialized and sorted selectedAllDataPoints with', selectedAllDataPoints.value.length, 'data points');
  }
  
  // 如果未开始播放且尚未选择任何数据点，不显示任何数据点
  if (!props.isPlaying && selectedAllDataPoints.value.length === 0) {
    return [];
  }
  
  // 获取当前播放时间（毫秒级时间）
  let currentPlaybackTime = props.currentPlaybackTime;
  console.log('props.currentPlaybackTime (ms):', currentPlaybackTime);
  
  // 确保有合理的默认值
  if (isNaN(currentPlaybackTime) || currentPlaybackTime < 0) {
    currentPlaybackTime = 0;
    console.warn('修正无效的当前时间值为0');
  }
  
  console.log('数据筛选过程开始 - 播放状态:', props.isPlaying, '| 当前播放时间:', currentPlaybackTime);
  console.log('总数据点数量:', selectedAllDataPoints.value.length);
  
  // 遍历所有数据点，筛选出时间在指定范围内的数据点
  const filteredData = selectedAllDataPoints.value.filter(point => {
    // 使用sysTime（直接从时间字符串转换的毫秒数）或直接转换time字符串
    const pointTime = point.sysTime || convertTimeStrToMs(point.time);
    
    // 检查是否有startTime传入
    if (props.startTime !== null && props.startTime !== undefined) {
      // 如果有startTime，筛选出时间在startTime和currentPlaybackTime之间的数据点
      const isMatch = pointTime >= props.startTime && pointTime <= currentPlaybackTime;
      
      // 对于范围内的数据点添加日志
      if (isMatch && Math.abs(pointTime - currentPlaybackTime) < 1000) {
        console.log('时间范围内匹配点:', { 
          sysTime: point.sysTime, 
          time: point.time, 
          x: point.x, 
          y: point.y,
          startTime: props.startTime,
          currentPlaybackTime: currentPlaybackTime,
          difference: Math.abs(pointTime - currentPlaybackTime) + 'ms'
        });
      }
      
      return isMatch;
    } else {
      // 如果没有startTime，保持原有逻辑，筛选出时间小于等于当前时间的数据点
      const isMatch = pointTime <= currentPlaybackTime;
      
      // 对于与当前播放时间接近的数据点添加日志
      if (Math.abs(pointTime - currentPlaybackTime) < 1000) { // 修改为1000ms的匹配范围
        console.log('关键匹配点:', { 
          sysTime: point.sysTime, 
          time: point.time, 
          x: point.x, 
          y: point.y,
          difference: Math.abs(pointTime - currentPlaybackTime) + 'ms'
        });
      }
      
      return isMatch;
    }
  });
  
  // 记录筛选前后的数据点数量变化
  console.log('数据筛选完成 - 匹配到的数据点数量:', filteredData.length);
  
  // 使用副作用watch而不是在计算属性中修改响应式数据
  // 避免循环依赖导致的多次计算
  isNoData.value = filteredData.length === 0;
  
  // 如果当前没有数据，发出无数据事件
  if (isNoData.value) {
    console.log('没有匹配到任何数据点');
    emit('no-data');
  }
  
  console.log('Display data updated with', filteredData.length, 'points for current time:', currentPlaybackTime);
  return filteredData;
})

// 监听currentIndex的变化，确保图表正确更新
watch(() => currentIndex.value, (newIndex) => {
  if (newIndex >= 0 && chartRef.value && hasData.value) {
    console.log('Watch: currentIndex changed to:', newIndex);
    // 强制更新图表以显示最新数据
    chartRef.value.resize(); // 触发图表重绘
  }
})

// 移除displayedData的watch，避免不必要的更新循环

// 监听播放状态变化
watch(() => props.isPlaying, (isPlaying, oldValue) => {
  console.log('播放状态变更:', { 从: oldValue ? '播放' : '暂停', 到: isPlaying ? '播放' : '暂停' });
  if (isPlaying && hasData.value) {
    console.log('开始播放 - 当前进度时间:', currentProgressTime.value, '秒');
    // 不需要额外检查，displayData计算属性会根据props.isPlaying和props.currentPlaybackTime自动更新
    // 避免使用displayedData.value导致的循环依赖
  } else if (!isPlaying) {
    console.log('暂停播放 - 暂停时间:', currentProgressTime.value, '秒');
  }
})

const chartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        if (params && params.length > 0) {
          const dataIndex = params[0].dataIndex
          const point = displayData.value[dataIndex]
          if (point) {
            return `
              <div>
                <strong>时间:</strong> ${point.time}<br/>
                <strong>X值:</strong> ${point.x}<br/>
                <strong>Y值:</strong> ${point.y}
              </div>
            `
          }
        }
        return ''
      }
    },
    grid: {
      left: '1%',
      right: '1%',
      bottom: '1%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: displayData.value.map(point => point.time),
      axisLabel: {
        rotate: 0,
        fontSize: 12,
        color: '#333',
        interval: 'auto',
        hideOverlap: true,
        margin: 15,
        formatter: function(value) {
          return value.substring(0, 5);
        }
      },
      axisTick: {
        alignWithLabel: true,
        length: 6,
        lineStyle: {
          color: '#666'
        }
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#666',
          width: 2
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: 'X轴数据',
        type: 'line',
        data: displayData.value.map(point => point.x),
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: {
          width: 2,
          color: '#409EFF'
        }
      },
      {
        name: 'Y轴数据',
        type: 'line',
        data: displayData.value.map(point => point.y),
        smooth: true,
        symbol: 'circle',
        symbolSize: 4,
        lineStyle: {
          width: 2,
          color: '#67C23A'
        }
      }
    ]
  }
})



// 暴露方法给父组件
defineExpose({
  setCurrentIndex: (index) => {
    if (index >= 0 && index <= maxIndex.value) {
      currentIndex.value = index;
    }
  },
  // 根据时间查找并加载数据点
  seekToTime: (time) => {
    console.log('HistoricalChart seekToTime called with time:', time);
    if (hasData.value) {
      console.log('Historical data length:', props.historicalData.length);
      
      // 确保selectedAllDataPoints已初始化并排序
      if (selectedAllDataPoints.value.length === 0) {
        selectedAllDataPoints.value = [...props.historicalData].sort((a, b) => {
          const timeA = a.sysTime || (typeof a.time === 'string' ? convertTimeStrToMs(a.time) : 0);
          const timeB = b.sysTime || (typeof b.time === 'string' ? convertTimeStrToMs(b.time) : 0);
          return timeA - timeB;
        });
        console.log('Initialized and sorted selectedAllDataPoints with', selectedAllDataPoints.value.length, 'data points');
      }
      
      // 使用传入的时间（毫秒）直接与数据点的sysTime进行比较
      const targetTime = time;
      
      // 遍历所有数据点，找到与当前时间最接近的索引
      let targetIndex = 0;
      let lastValidTime = 0;
      let closestPoint = null;
      
      console.log('时间匹配过程开始 - 目标时间 (ms):', targetTime);
      
      // 优先使用selectedAllDataPoints进行索引计算
      for (let i = 0; i < selectedAllDataPoints.value.length; i++) {
        const point = selectedAllDataPoints.value[i];
        // 使用sysTime或转换time字符串为毫秒
        const pointTime = point.sysTime || convertTimeStrToMs(point.time);
        
        console.log(`比较数据点 #${i}: sysTime=${pointTime}, 时间=${point.time}, 是否匹配: ${pointTime <= targetTime}`);
        
        if (pointTime <= targetTime) {
          targetIndex = i;
          lastValidTime = pointTime;
          closestPoint = point;
        } else {
          console.log(`找到第一个大于目标时间的数据点 #${i}, 停止搜索`);
          break; // 因为数据已经按时间排序，所以一旦找到第一个大于当前时间的点，就可以停止
        }
      }
      
      // 修复语法错误的console.log语句
      console.log('时间匹配结果:', { 
        targetTime: targetTime, 
        matchedIndex: targetIndex,
        lastValidTime: lastValidTime,
        matchedDataPoint: closestPoint ? {
          sysTime: closestPoint.sysTime,
          time: closestPoint.time,
          x: closestPoint.x,
          y: closestPoint.y,
          difference: closestPoint ? Math.abs(closestPoint.sysTime - targetTime) + 'ms' : null
        } : null
      });
      
      if (targetIndex >= 0 && targetIndex < selectedAllDataPoints.value.length) {
        // 强制更新currentIndex，确保图表更新
        currentIndex.value = -1;
        // 存储当前进度条的播放时间（秒）
        currentProgressTime.value = time;
        // 使用setTimeout确保响应式更新生效
        setTimeout(() => {
          currentIndex.value = targetIndex;
          console.log('Set currentIndex to:', targetIndex);
        }, 0);
      }
    }
  }
})
</script>

<style scoped>
.historical-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-header {
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.chart-header h4 {
  margin: 0;
  color: #333;
  font-size: 14px;
}

.chart-container {
  flex: 1;padding: 10px;
}

.chart {
  flex: 1;
  min-height: 200px;
}
  .no-data-message {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: #999;
    background-color: #fafafa;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
  }
</style>
